package com.kelaite.procurement.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.kelaite.procurement.common.CommonResponseDto;
import com.kelaite.procurement.common.RetCodeEnum;
import com.kelaite.procurement.dto.SalesOrderItemsDTO;
import com.kelaite.procurement.dto.UserDTO;
import com.kelaite.procurement.entity.TBank;
import com.kelaite.procurement.entity.TCompany;
import com.kelaite.procurement.entity.TIndustry;
import com.kelaite.procurement.entity.TMessage;
import com.kelaite.procurement.entity.TOrganizationType;
import com.kelaite.procurement.entity.TPaidList;
import com.kelaite.procurement.entity.TPipelineHeader;
import com.kelaite.procurement.entity.TPipelineItem;
import com.kelaite.procurement.entity.TPipelinePublic;
import com.kelaite.procurement.entity.TProvince;
import com.kelaite.procurement.entity.TPurchaseOrder;
import com.kelaite.procurement.entity.TSalesOrder;
import com.kelaite.procurement.entity.TSalesOrderItems;
import com.kelaite.procurement.entity.TSalesOrderPayment;
import com.kelaite.procurement.entity.TUser;
import com.kelaite.procurement.entity.TVendor;
import com.kelaite.procurement.repository.PaidListRepository;
import com.kelaite.procurement.repository.PipelineItemRepository;
import com.kelaite.procurement.repository.PipelinePublicRepository;
import com.kelaite.procurement.repository.SalesOrderRepository;
import com.kelaite.procurement.restful.BaseController;
import com.kelaite.procurement.service.BankService;
import com.kelaite.procurement.service.CompanyService;
import com.kelaite.procurement.service.IndustryService;
import com.kelaite.procurement.service.MessageService;
import com.kelaite.procurement.service.OrganizationTypeService;
import com.kelaite.procurement.service.PaidListService;
import com.kelaite.procurement.service.PipelineHeaderService;
import com.kelaite.procurement.service.PipelineItemService;
import com.kelaite.procurement.service.PipelinePublicService;
import com.kelaite.procurement.service.ProvinceService;
import com.kelaite.procurement.service.PurchaseOrderExecutionItemsService;
import com.kelaite.procurement.service.PurchaseOrderExecutionService;
import com.kelaite.procurement.service.PurchaseOrderItemsService;
import com.kelaite.procurement.service.PurchaseOrderService;
import com.kelaite.procurement.service.SalesOrderExecutionItemsService;
import com.kelaite.procurement.service.SalesOrderExecutionService;
import com.kelaite.procurement.service.SalesOrderItemsService;
import com.kelaite.procurement.service.SalesOrderPaymentService;
import com.kelaite.procurement.service.SalesOrderService;
import com.kelaite.procurement.service.UserService;
import com.kelaite.procurement.service.VendorService;
import com.kelaite.procurement.utils.ConvertTime;
import com.kelaite.procurement.utils.CurrentUserUtils;
import com.kelaite.procurement.utils.FileUpload;
import com.kelaite.procurement.utils.JsonUtil;

/**
 * 
 * @author yuanchangwei
 *
 */
@Controller
@RequestMapping("/supplier/")
public class SupplierController extends BaseController{
	
	@Autowired
	private PipelineHeaderService pipelineHeaderService;
	
	@Autowired
	private PipelineItemService pipelineItemService;

	@Autowired
	private PipelinePublicService pipelinePublicService;
	
	@Autowired
	private VendorService vendorService;
	
	@Autowired
	private UserService userService;
	@Autowired
	private PurchaseOrderService purchaseOrderService;
	
	@Autowired
	private SalesOrderService salesOrderService;

	@Autowired
	private SalesOrderPaymentService salesOrderPaymentService;
	
	@Autowired
	private SalesOrderItemsService salesOrderItemsService;
	
	@Autowired
	private SalesOrderExecutionService salesOrderExecutionService;
	
	@Autowired
	private SalesOrderExecutionItemsService salesOrderExecutionItemService;
	
	@Autowired
	private PurchaseOrderItemsService purchaseOrderItemsService;
	
	@Autowired
	private PurchaseOrderExecutionService purchaseOrderExecutionService;
	
	@Autowired
	private PurchaseOrderExecutionItemsService purchaseOrderExecutionItemService;
	
	@Autowired
	private ProvinceService provinceService;
	
	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private IndustryService industryService;
	
	@Autowired
	private OrganizationTypeService organizationTypeService;
	
	@Autowired
	private BankService bankService;
	
	@Autowired
	private MessageService messageService;
	
	@Autowired
	private PaidListService paidListService;
	
	@Autowired
	private PaidListRepository paidListRepository;
	
	@Autowired
	private PipelineItemRepository pipelineItemRepository;
	
	@Autowired
	private PipelinePublicRepository pipelinePublicRepository;
	
	@Autowired
	private SalesOrderRepository salesOrderRepository;
	
	@RequestMapping(value = "/index", method = {RequestMethod.GET, RequestMethod.POST})
	public String index(Model model,HttpServletRequest request) {
		
		//销售机会列表
				UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
			    TUser currentUser = this.userService.getObject(userDTO.getId());
				
			    List<TVendor> vendorList = this.vendorService.getByProperty("tSupplier", currentUser.gettCompany());
				TVendor vendor = vendorList.get(0);
				TCompany[] companyObjects = new TCompany[vendorList.size()];
				for(int size = 0; size < vendorList.size(); size++){
					companyObjects[size] = vendorList.get(size).gettClient();
				}
				//所有和关系公司的招标信息
				List<TPipelineItem> pipelineItems = this.pipelineItemService.findByCompany(companyObjects);
				
				
				TPipelineItem pipelineItemsAfter = null ;
				for (int i = 0 ; i<pipelineItems.size();i++){
					//closeTime
					Date now = new Date();
					Date closeTime = pipelineItems.get(i).getCloseTime();
					if(closeTime!=null&&now.after(closeTime)){
						pipelineItemsAfter = pipelineItems.get(i);
						break;
					}
				}
				
				
				model.addAttribute("pipelineItemsAfter", pipelineItemsAfter);
				
				//所有当前用户参与过的招标信息列表t_pipeline_header : id
				List<Long> pipelineHeaderIds = this.pipelinePublicService.findPipelineHeaderIdsByVendor(vendor);
				TPipelineItem pipelineItem =null;
				if(pipelineItems.size()>0)
				{
					pipelineItem  = pipelineItems.get(0);
				}
				
				model.addAttribute("vendorList", vendorList);
				model.addAttribute("pipelineItem", pipelineItem);
				model.addAttribute("pipelineHeaderIds", pipelineHeaderIds);
				
			  
		
		//TODO
	    
	    //所有和关系公司的招标信息
	    //T_pipeline表中，行业和vendor的行业相符，或bid_type为2、3、4，且company_id中有vendor公司的，当前时间早于close_time的，统计条数
	    int xiaoshoujihui = pipelineItems.size();
	    //销售订单，T_sales_order，所有符合vendor号、order_status为0、1、2的统计条数
	    int xiaoshoudingdan = 0 ;
	    List<TSalesOrder> salesOrderList = this.salesOrderService.getByProperty("tVendor", vendor);
	    for (int i = 0 ; i<salesOrderList.size() ; i++){
	    	TSalesOrder salesOrder = salesOrderList.get(i);
	    	if(!salesOrder.getOrderStatus().equals(3)){
	    		xiaoshoudingdan = xiaoshoudingdan+1 ;
	    	}
	    }
		   //我的消息,T_message，未读条数
	    int message = 0 ;
	    List<TMessage> messageList = this.messageService.getByProperty("tReceiver",currentUser );
	    for (int i = 0 ; i< messageList.size() ;i++){
	    	TMessage Tmessage = messageList.get(i);
	    	if(Tmessage.getReadStatus()==0){
	    		message =message +1 ;
	    	}
	    }
	    //T_paid_list，会员至**时间
	    List<TPaidList> tPaidList = this.paidListRepository.getPaidListOrderByTime(currentUser.gettCompany().getId());
	    String huiyuanshijian = "";
	    if(tPaidList!=null&&tPaidList.size()>0){
	    	huiyuanshijian = (new SimpleDateFormat("yyyy-MM-dd")).format(tPaidList.get(0).getGmtUpdateTime());
	    }
	    model.addAttribute("huiyuanshijian", huiyuanshijian);
	    model.addAttribute("message", message);
	    model.addAttribute("xiaoshoujihui", xiaoshoujihui);
	    model.addAttribute("vendor", vendor);
		model.addAttribute("currentUser", currentUser);
		model.addAttribute("xiaoshoudingdan", xiaoshoudingdan);
		
		/*****子表数据*****/
		//T_pipeline
		List<TPipelineItem> tPipelineItemList = this.pipelineItemRepository.getPipelineItemOrderByTime(currentUser.gettCompany().getId());
		TPipelineItem tPipelineItem = new TPipelineItem();
		if(tPipelineItemList!=null&& tPipelineItemList.size()>0){
			tPipelineItem = tPipelineItemList.get(0);
		}
		model.addAttribute("tPipelineItem", tPipelineItem);
		
		//T_pipeline_public
		List<TPipelinePublic> tPipelinePublicList = this.pipelinePublicRepository.getPipelinePublicOrderByTime(currentUser.getId());
		TPipelinePublic tPipelinePublic = new TPipelinePublic();
		if(tPipelinePublicList!=null && tPipelinePublicList.size()>0){
			tPipelinePublic = tPipelinePublicList.get(0);		
			model.addAttribute("tPipelinePublic", tPipelinePublic);
		}
		else
		{
			model.addAttribute("tPipelinePublic", null);
		}
		
		//T_sales_order  create_time
		List<TSalesOrder> tSalesOrderList = this.salesOrderRepository.getSalesOrderOrderByTime(currentUser.gettCompany().getId());
		TSalesOrder tSalesOrder = new TSalesOrder();
		if(tSalesOrderList!=null&& tSalesOrderList.size()>0){
			tSalesOrder=tSalesOrderList.get(0);	
			model.addAttribute("tSalesOrder", tSalesOrder);
		}
		else
		{
			model.addAttribute("tSalesOrder", null);
		}
		
		//T_sales_order，evaluation_time
		List<TSalesOrder> tSalesOrderList_evaluation = this.salesOrderRepository.getSalesOrderOrderByEvaluationTime(currentUser.gettCompany().getId());
		TSalesOrder tSalesOrder_evaluation = new TSalesOrder();
		if(tSalesOrderList_evaluation!=null&& tSalesOrderList_evaluation.size()>0){
			tSalesOrder_evaluation=tSalesOrderList_evaluation.get(0);
		}
		model.addAttribute("tSalesOrderEvaluation", tSalesOrder_evaluation);
		
		
		return "supplier/supplier_index";
	}
	
	@RequestMapping(value = "/saleList", method = {RequestMethod.GET, RequestMethod.POST})
	public String saleList(Model model, HttpServletRequest request) {
		//销售机会列表
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
	    TUser currentUser = this.userService.getObject(userDTO.getId());
		
	    List<TVendor> vendorList = this.vendorService.getByProperty("tSupplier", currentUser.gettCompany());
		TVendor vendor = vendorList.get(0);
		TCompany[] companyObjects = new TCompany[vendorList.size()];
		for(int size = 0; size < vendorList.size(); size++){
			companyObjects[size] = vendorList.get(size).gettClient();
		}
		//所有和关系公司的招标信息
		List<TPipelineItem> pipelineItems = this.pipelineItemService.findByCompany(companyObjects);
		
		//所有当前用户参与过的招标信息列表t_pipeline_header : id
		List<Long> pipelineHeaderIds = this.pipelinePublicService.findPipelineHeaderIdsByVendor(vendor);
		
		model.addAttribute("vendorList", vendorList);
		model.addAttribute("pipelineItems", pipelineItems);
		model.addAttribute("pipelineHeaderIds", pipelineHeaderIds);
		
		return "supplier/sale_list";
	}
	
	@RequestMapping(value = "/participatePipeline", method = {RequestMethod.GET, RequestMethod.POST})
	public String participatePipeline(Model model, HttpServletRequest request) {
		String pipelineId = request.getParameter("pipelineId");
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
		TUser currentUser = this.userService.getObject(userDTO.getId());
		
		TPipelineHeader pipelineHeader = this.pipelineItemService.getObject(Long.parseLong(pipelineId)).gettPipelineHeader();
		
		TVendor vendor = this.vendorService.getVendorByClientAndSupplier(pipelineHeader.gettCompany(), currentUser.gettCompany());
		
		boolean flag = this.pipelinePublicService.ifAlreadyPipelined(pipelineHeader, vendor);
		
		@SuppressWarnings("unused")
		String errorMsg = "";
		
		if(flag == true){
			request.setAttribute("errorMsg", "提示: 您已经参与过此次投标!");
			return this.saleList(model, request);   //已进标过
		}else{
			TPipelinePublic pipelinePublic = new TPipelinePublic();
			pipelinePublic.setCreatedBy(currentUser.getUsername());
			pipelinePublic.setDelete(false);
			pipelinePublic.setFinalWin(false);
			pipelinePublic.setGmtCreateTime(new Date());
			pipelinePublic.setGmtUpdateTime(new Date());
			pipelinePublic.setSuggestedWin(false);
			pipelinePublic.setCreateContract(false);
			pipelinePublic.settPipelineHeader(pipelineHeader);
			pipelinePublic.settVendor(vendor);
			pipelinePublic.setUpdatedBy(currentUser.getUsername());
			if(this.pipelinePublicService.save(pipelinePublic) != null){
				logger.debug("process pipeline success!");
				request.setAttribute("errorMsg", "投标成功!");  //参与竞标
			}
		}
		return this.saleList(model, request);   //已进标过
	}
	
	@RequestMapping(value = "/notParticipatePipeline", method = {RequestMethod.GET, RequestMethod.POST})
	public String notParticipatePipeline(Model model, HttpServletRequest request) {
		String pipelineId = request.getParameter("pipelineId");
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
		TUser currentUser = this.userService.getObject(userDTO.getId());
		
		TPipelineHeader pipelineHeader = this.pipelineItemService.getObject(Long.parseLong(pipelineId)).gettPipelineHeader();
		TVendor vendor = this.vendorService.getVendorByClientAndSupplier(pipelineHeader.gettCompany(), currentUser.gettCompany());
		TPipelinePublic pipelinePublic = this.pipelinePublicService.findByPipelineHeaderAndVendor(pipelineHeader, vendor);
		
		if(pipelinePublic.isFinalWin() == true){
			request.setAttribute("errorMsg", "您已中标,不能删除！");
			return this.saleList(model, request);   //已进标过
		}else{
			this.pipelinePublicService.deleteByPrimaryKey(pipelinePublic.getId());
			request.setAttribute("errorMsg", "删除成功！");
		}
		return this.saleList(model, request);   //已进标过
	}
	
	@RequestMapping(value = "/updateBidPrice", method = {RequestMethod.GET, RequestMethod.POST})
	public String updateBidPrice(Model model, HttpServletRequest request) {
		String pipelinePublidId = request.getParameter("pipelinePublidId");
		String bidPrice = request.getParameter("bidPrice");
		TPipelinePublic pipelinePublic = this.pipelinePublicService.getObject(Long.parseLong(pipelinePublidId));
		pipelinePublic.setBidPrice(Long.parseLong(bidPrice));
		this.pipelinePublicService.save(pipelinePublic);
		request.setAttribute("errorMsg", "报价成功 ! 金额为：" + bidPrice);
		return this.saleList(model, request); 
	}
	public Integer isNull (Integer value){
		if(value==null||value.equals("")||value==0){
			return 0;
		}else{
			return value;
		}
	}
	
	@RequestMapping(value = "/orderList", method = {RequestMethod.GET, RequestMethod.POST})
	public String orderList(Model model,HttpServletRequest request) {
		//销售订单
		
		String orderStatusStr=request.getParameter("orderStatus");
		Short orderStatus=5;//5代表全部订单，2是已完成订单，1是待履行订单
		if(orderStatusStr!=null)
		{
			orderStatus =Short.parseShort(request.getParameter("orderStatus"));
		}	
		
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
	    TUser currentUser = this.userService.getObject(userDTO.getId());
		
	    List<TVendor> vendorList = this.vendorService.getByProperty("tSupplier", currentUser.gettCompany());
		@SuppressWarnings("unused")
		TVendor vendor = vendorList.get(0);
		List<TSalesOrder> salesOrders;
		
		salesOrders= this.salesOrderService.getByPropertyByStatus("tCompany",vendor.gettSupplier(),orderStatus);//(vendor.gettClient());	
//		int a=salesOrders.get(0).gettSalesOrderItems().size();
		//milestone_type状态暂存字段
				for(int i=0 ; i<salesOrders.size();i++){
					Set<TSalesOrderPayment> oldtPurchaseOrderPaymentSet = salesOrders.get(i).gettSalesOrderPayment();
					List<TSalesOrderPayment> oldtPurchaseOrderPaymentList = new ArrayList<TSalesOrderPayment>(oldtPurchaseOrderPaymentSet);
					List<TSalesOrderPayment> tPurchaseOrderPaymentList = new ArrayList<TSalesOrderPayment>();
					for(int j = 0 ; j <oldtPurchaseOrderPaymentList.size() ; j++){
						TSalesOrderPayment oldtPurchaseOrderPayment = oldtPurchaseOrderPaymentList.get(j);
					    Integer	deliveryNote1 = isNull(oldtPurchaseOrderPayment.getDeliveryNote1());
					    Integer deliveryNoteAttachmentStatus1 = isNull(oldtPurchaseOrderPayment.getDeliveryNoteAttachmentStatus1());
					    Integer acceptanceReportAttachmentStatus = isNull(oldtPurchaseOrderPayment.getAcceptanceReportAttachmentStatus());
					    Integer invoiceAttachmentStatus1  = isNull(oldtPurchaseOrderPayment.getInvoiceAttachmentStatus1());
					    Long paidAmount = oldtPurchaseOrderPayment.getPaidAmount();
					    Long billedAmount =  oldtPurchaseOrderPayment.getBilledAmount();
					    //待发货  所有字段=0
					    if(deliveryNote1== 0 &&deliveryNoteAttachmentStatus1==0 && acceptanceReportAttachmentStatus==0 
					    		&&invoiceAttachmentStatus1 == 0 && (paidAmount==null||paidAmount==0)
					    		&& (billedAmount==null||billedAmount==0)){
					    	oldtPurchaseOrderPayment.setMilestoneType((short)1);
					    }
					    //已发货   delivery_note_1=1；其他字段=0
					     if (deliveryNote1==1&&deliveryNoteAttachmentStatus1==0 && acceptanceReportAttachmentStatus==0 
					    		&&invoiceAttachmentStatus1 == 0 && (paidAmount==null||paidAmount==0)
					    		&& (billedAmount==null||billedAmount==0)){
					    	oldtPurchaseOrderPayment.setMilestoneType((short)2);
					    }
					    //已验货  delivery_note_1=1 and delivery_note_attachment_status_1=1 且其他字段等于0
					     if(deliveryNote1==1&&deliveryNoteAttachmentStatus1==1 && acceptanceReportAttachmentStatus==0 
					    		&&invoiceAttachmentStatus1 == 0 && (paidAmount==null||paidAmount==0)
					    		&& (billedAmount==null||billedAmount==0)){
					    	oldtPurchaseOrderPayment.setMilestoneType((short)3);
					    }
					    //已验收  acceptance_report_attachment_status=1 且 invoice_attachment_status_1=0
					     if (acceptanceReportAttachmentStatus==1  &&invoiceAttachmentStatus1 == 0 ){
					    	oldtPurchaseOrderPayment.setMilestoneType((short)4);
					    }
					    //已收发票 invoice_attachment_status_1=1 且 paid amount<billed amount
					     if (invoiceAttachmentStatus1==1 && paidAmount!=null && billedAmount!=null && (paidAmount<billedAmount)){
					    	oldtPurchaseOrderPayment.setMilestoneType((short)5);
					    }
					    //已付款  paid amount = billed amount
					     if (paidAmount!=null&&billedAmount!=null&&paidAmount!=0&&billedAmount!=0&&paidAmount==billedAmount){
					    	oldtPurchaseOrderPayment.setMilestoneType((short)6);
					    }
					     tPurchaseOrderPaymentList.add(oldtPurchaseOrderPayment);
					     
					}
					
					Set<TSalesOrderPayment> set = new HashSet<TSalesOrderPayment>(tPurchaseOrderPaymentList);
					salesOrders.get(i).settSalesOrderPayment(set);
					
				}
		
//		for(int i= 0 ;i <salesOrders.size() ;i++){
//			 Set<TSalesOrderItems>  a = salesOrders.get(i).gettSalesOrderItems();
//			 List<TSalesOrderItems> b = new ArrayList<TSalesOrderItems>(a);
//			 for (int j = 0 ; j< b.size(); j++){
//				 System.out.println("planedTime------------" +b.get(j).getPlanedTime());
//				 System.out.println("actualTime------------" +b.get(j).getActualTime());
//			 }
//			 
//			 
//		}
//		
	   
		model.addAttribute("salesOrders", salesOrders);
		
		model.addAttribute("orderStatus",orderStatus);
		return "supplier/order_list";
	}
	
	@SuppressWarnings({ "rawtypes"})
	@RequestMapping(value = "/CreateOrderDelivery", method = RequestMethod.POST)
	@ResponseBody
	public String createOrderDelivery(@RequestBody List<SalesOrderItemsDTO> salesOrderItems,Model model,HttpServletRequest request) {
		
		try
		{
			UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
			TUser currentUser = this.userService.getObject(userDTO.getId());
			
			List<TVendor> vendorList = this.vendorService.getByProperty("tSupplier", currentUser.gettCompany());
			String checkValue="";
			for(int i = 0 ; i< salesOrderItems.size(); i++){
				checkValue= checkValue+ (i+1)+",";
				if((i+1)==salesOrderItems.size()){
					checkValue= checkValue+ (i+1);
				}
			}
//			String checkValue=request.getParameter("checkData");

			//更新SalesOrderItems及一系列相关表
			this.salesOrderItemsService.updateSalesOrderItems(salesOrderItems,currentUser,vendorList);
		
			return JsonUtil.serialize(new CommonResponseDto(RetCodeEnum.SUCCESS.getCode(), RetCodeEnum.SUCCESS.getMsg()));
		}
		catch(Exception e)
		{
			return JsonUtil.serialize(new CommonResponseDto<String>(
					RetCodeEnum.FAIL.getCode(), e.getMessage()));
		}
	}
	
	@RequestMapping(value = "/preCreateOrder", method = {RequestMethod.GET, RequestMethod.POST})
	public String preCreate(Model model) {
		return "supplier/create_order";
	}
	
	@RequestMapping(value = "/preCreateDelivery", method = {RequestMethod.GET, RequestMethod.POST})
	public String preCreateDelivery(Model model,HttpServletRequest request) {
		
		String a=request.getParameter("salesOrderID");
		//Long salesOrderId =Long.parseLong(request.getParameter("salesOrderID"));
		Long salesOrderId =Long.parseLong(a);
		
		TSalesOrder salesOrder = this.salesOrderService.getObject(salesOrderId);
		model.addAttribute("salesOrder", salesOrder);
		
		
		Set<TSalesOrderItems> tSalesOrderItems = salesOrder.gettSalesOrderItems();
		List<TSalesOrderItems> tSalesOrderItemsList = new ArrayList<TSalesOrderItems>(tSalesOrderItems);
		List<TSalesOrderItems> tempSalesOrderItemsList = new ArrayList<TSalesOrderItems>(tSalesOrderItems);
		//过滤最大可发货<0的订单
		for(int i=0;i<tempSalesOrderItemsList.size();i++)
		{
			TSalesOrderItems saleItem=tempSalesOrderItemsList.get(i);
			if(saleItem.getQuantity()!=null && saleItem.getQuantityDelivered()!=null)
			{
				if((saleItem.getQuantity()-saleItem.getQuantityDelivered())<=0)
				{
					tSalesOrderItemsList.remove(saleItem);
				}
			}
		}
		
		model.addAttribute("salesOrderItems", tSalesOrderItemsList);
		model.addAttribute("tSalesOrderItems",new TSalesOrderItems());
		Date date = new Date();
	    long time = date.getTime();
	    model.addAttribute("date", time);
		
		return "supplier/create_order_delivery";
	}
	
	/**
	 * 订单验收申请
	 * 
	 * 入参： sales order id
	 * 
	 * author wangjunxi
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/checkOrder", method = {RequestMethod.GET, RequestMethod.POST})
	public String checkOrder(Model model,HttpServletRequest request) {
		//TODO
		//查询salesOrder表
		String salesOrderNo =request.getParameter("salesOrderID");
		List<TSalesOrder> salesOrders = this.salesOrderService.getByProperty("id",Long.parseLong(salesOrderNo));
		TSalesOrder salesOrder = salesOrders.get(0);
		Set<TSalesOrderPayment> tSalesOrderPayment =salesOrder.gettSalesOrderPayment();
		
		List<TSalesOrderPayment> tSalesOrderPaymentList = new ArrayList<TSalesOrderPayment>(tSalesOrderPayment);
		model.addAttribute("tSalesOrderPayment",new TSalesOrderPayment());
		model.addAttribute("salesOrder", salesOrder);
		model.addAttribute("tSalesOrderPaymentList" , tSalesOrderPaymentList);
		Long paidAmount = (long) 0 ;
		Long planAmount = (long) 0 ;
		for (int i =  0 ; i< tSalesOrderPaymentList.size();i++){
			if(tSalesOrderPaymentList.get(i).getPaidAmount()!=null){
				paidAmount=paidAmount+tSalesOrderPaymentList.get(i).getPaidAmount();
			}
			if(tSalesOrderPaymentList.get(i).getPlanAmount()!=null){
				planAmount=planAmount+tSalesOrderPaymentList.get(i).getPlanAmount();
			}
		}
		
		model.addAttribute("baiFenBi", paidAmount/planAmount);
		
		
		Date date = new Date();
		long time = date.getTime();
		model.addAttribute("date", time);
		return "supplier/check_order";
	}
	
	@RequestMapping(value = "/checkOrderInsert", method = {RequestMethod.GET, RequestMethod.POST})
	public String checkOrderInsert(@RequestParam("btnFileBG") MultipartFile btnFileBG,@RequestParam("FPbtnFile") MultipartFile FPbtnFile,@Valid @ModelAttribute("tSalesOrderPayment") TSalesOrderPayment tSalesOrderPayment,Model model,HttpServletRequest request) {
		//TODO
		String a = request.getParameter("realTime1");
		Long billedAmount =tSalesOrderPayment.getBilledAmount();
		Float increamentTax1=tSalesOrderPayment.getIncreamentTax();
		Float amountWithoutTax1=tSalesOrderPayment.getAmountWithoutTax();
		if(amountWithoutTax1!=null&&increamentTax1!=null&&billedAmount!=null&&(increamentTax1+amountWithoutTax1)==billedAmount){
//			return "supplier/order_list";
			model.addAttribute("success", 1);
			String salesOrderPaymentID =request.getParameter("salesOrderID");
			List<TSalesOrderPayment> salesOrderPaymentList = this.salesOrderPaymentService.getByProperty("id",Long.parseLong(salesOrderPaymentID));
			TSalesOrderPayment salesOrderPayment = salesOrderPaymentList.get(0);
			
			if(a!=null&&!a.equals("")){
			salesOrderPayment.setRealTime(ConvertTime.StringToDate2(a));
			}
			salesOrderPayment.setOrderPaymentRemark(tSalesOrderPayment.getOrderPaymentRemark());
			salesOrderPayment.setPaidAmount(tSalesOrderPayment.getPaidAmount());
			String salesOrderNoTo =salesOrderPayment.gettSalesOrder().getSalesOrderNo();
			this.salesOrderPaymentService.save(salesOrderPayment);
			//获取数据
			request.setAttribute("salesOrderNo", salesOrderNoTo);
			checkOrder( model, request);
			
			
		}else if(amountWithoutTax1!=null&&increamentTax1!=null&&billedAmount!=null){
			//数值相加错了
			model.addAttribute("success", 2);
			String salesOrderPaymentID =request.getParameter("salesOrderID");
			List<TSalesOrderPayment> salesOrderPaymentList = this.salesOrderPaymentService.getByProperty("id",Long.parseLong(salesOrderPaymentID));
			TSalesOrderPayment salesOrderPayment = salesOrderPaymentList.get(0);
			
			if(a!=null&&!a.equals("")){
			salesOrderPayment.setRealTime(ConvertTime.StringToDate2(a));
			}
			salesOrderPayment.setOrderPaymentRemark(tSalesOrderPayment.getOrderPaymentRemark());
			salesOrderPayment.setPaidAmount(tSalesOrderPayment.getPaidAmount());
			String salesOrderNoTo =salesOrderPayment.gettSalesOrder().getSalesOrderNo();
			//获取数据
			request.setAttribute("salesOrderNo", salesOrderNoTo);
			checkOrder( model, request);
		}else{
			//有参数没有填写
			model.addAttribute("success", 3);
			
			String salesOrderPaymentID =request.getParameter("salesOrderID");
			List<TSalesOrderPayment> salesOrderPaymentList = this.salesOrderPaymentService.getByProperty("id",Long.parseLong(salesOrderPaymentID));
			TSalesOrderPayment salesOrderPayment = salesOrderPaymentList.get(0);
			
			if(a!=null&&!a.equals("")){
			salesOrderPayment.setRealTime(ConvertTime.StringToDate2(a));
			}
			salesOrderPayment.setOrderPaymentRemark(tSalesOrderPayment.getOrderPaymentRemark());
			salesOrderPayment.setPaidAmount(tSalesOrderPayment.getPaidAmount());
			String salesOrderNoTo =salesOrderPayment.gettSalesOrder().getSalesOrderNo();
			//获取数据
			request.setAttribute("salesOrderNo", salesOrderNoTo);
			checkOrder( model, request);
		}
		
		return "supplier/check_order";
	}

	@Override
	protected Class<?> getCurrentClass() {
		return SupplierController.class;
	}
	
	@RequestMapping(value = "/companyMessage", method = {RequestMethod.GET, RequestMethod.POST})
	public String companyMessage(Model model,HttpServletRequest request) {
		//TODO
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
	    currentUser = this.userService.getObject(userDTO.getId());
	    List<TVendor> vendorList =null;
	    vendorList = this.vendorService.getByProperty("tSupplier", currentUser.gettCompany());
	    if(vendorList == null || vendorList.size()==0){
	    	vendorList = this.vendorService.getByProperty("tClient",currentUser.gettCompany());
	    }
	    vendor = vendorList.get(0);
	    model.addAttribute("currentUser", currentUser);
		model.addAttribute("vendor",vendor)	;	
		//vendor
		return "supplier/company_message";
	}
	
	public TUser currentUser ;
	public TVendor vendor ;
	
	
	@RequestMapping(value = "/changeToEdit", method = {RequestMethod.GET, RequestMethod.POST})
	public String changeToEdit(Model model,HttpServletRequest request) {
		
		List<TBank> bankList = bankService.getAll();
		List<TOrganizationType> orgList = organizationTypeService.getAll();
		List<TCompany> companyList = this.companyService.getAll();
		List<TProvince> pList = this.provinceService.getAll();
		List<TIndustry> industryList = this.industryService.getAll();
		model.addAttribute("bankList", bankList);
		model.addAttribute("orgList", orgList);
		model.addAttribute("industryList", industryList);
		model.addAttribute("pList", pList);
		model.addAttribute("companyList", companyList);
		model.addAttribute("currentUser", currentUser);
		model.addAttribute("vendor",vendor);
		//model.addAttribute("user",new TUser());
		model.addAttribute("company",new TCompany());
		return "supplier/company_message_edit";
	}
	
	@RequestMapping(value = "/orderCheck", method = {RequestMethod.GET, RequestMethod.POST})
	public String orderCheck(Model model,HttpServletRequest request) {
		//TODO
		
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
	    TUser currentUser = this.userService.getObject(userDTO.getId());
		
	    List<TVendor> vendorList = this.vendorService.getByProperty("tSupplier", currentUser.gettCompany());
		TVendor vendor = vendorList.get(0);
		
		
		List<TPurchaseOrder> tPurchaseOrder = this.purchaseOrderService.getByProperty("tVendor",vendor);
		model.addAttribute("purchaseOrderList", tPurchaseOrder);
		return "supplier/order_check";
	}
	
	@RequestMapping(value = "/changeUser", method = {RequestMethod.GET, RequestMethod.POST})	
	public String changeUser(@ModelAttribute("user") TUser user, BindingResult result, HttpServletRequest request, Model model){
		
		String companyId = request.getParameter("companyId");
		//TCompany company = companyService.getObject(Long.parseLong(companyId));
		@SuppressWarnings("unused")
		boolean success =this.userService.updateChangeUser(user.getRealName(), user.getMobilePhone(),
				Long.parseLong(companyId), user.getRoleIds(), user.getId());
		
		return companyMessage(model,request);
		
//		if (qUser == null){
//			
//			
//			// request.setAttribute("errorMsg", "用户注册成功!");
//			//  自动登录
//			UserDTO dto = ConvertUtil.convertObj(savedUser, UserDTO.class);
//			CurrentUserUtils.getInstance().setUser(dto);
//			return "redirect:/supplier/index.htm";
//		} else {
//			// 用户已经存在
//			request.setAttribute("errorMsg", "该用户已经存在！");
//			model.addAttribute("user", user);
//			this.init(model);			
//			return "register";
//		}
	}
	
	@RequestMapping(value = "/changeCompany", method = {RequestMethod.GET, RequestMethod.POST})	
	public String changeCompany(@ModelAttribute("company") TCompany company, BindingResult result, HttpServletRequest request, Model model){
		
		String companyId = request.getParameter("companyId");
		TCompany tempCompany = companyService.getObject(Long.parseLong(companyId));
		tempCompany.setCompanyName(company.getCompanyName());
		tempCompany.setBusinessId(company.getBusinessId());
		tempCompany.setAddress(company.getAddress());
		tempCompany.setRegisteredPhone(company.getRegisteredPhone());
		tempCompany.setRegisteredCapital(company.getRegisteredCapital());
		tempCompany.setOrganizationCode(company.getOrganizationCode());
		tempCompany.setTaxNo(company.getTaxNo());
		tempCompany.setIsGeneralTaspayer(company.getIsGeneralTaspayer());
		tempCompany.setBankAccount(company.getBankAccount());
		
		this.companyService.save(tempCompany);
		//boolean success=this.userService.updateChangeUser(user.getRealName(), user.getMobilePhone(),
				//Long.parseLong(companyId), user.getRoleIds(), user.getId());
		
		return companyMessage(model,request);
	}
	
	@RequestMapping(value = "/orderFileUpLoad", method = {RequestMethod.GET, RequestMethod.POST})	
	public void orderFileUpLoad(@RequestParam MultipartFile btnFile1,HttpServletRequest request,HttpServletResponse response)
	{
		UserDTO userDTO = CurrentUserUtils.getInstance().getUser();
	    TUser currentUser = this.userService.getObject(userDTO.getId());
		
	    List<TVendor> vendorList = this.vendorService.getByProperty("tSupplier", currentUser.gettCompany());
		TVendor vendor = vendorList.get(0);
		
		String fileName = btnFile1.getOriginalFilename();
		//fileName = request.getParameter("path");
		//File file = new File(fileName);
		//File file = new File(fileName);
        String ret = FileUpload.writeFile(btnFile1, fileName);
        String salesOrderID = request.getParameter("salesOrderID");
        String deliverOrderNo=request.getParameter("deliverOrderNo");
        
        salesOrderExecutionService.uploadSalesOrderExecutionFile(ret, Long.parseLong(salesOrderID), currentUser, vendor);
	}
	
	@RequestMapping(value = "/orderFileUpLoadFP", method = {RequestMethod.GET, RequestMethod.POST})	
	public void orderFileUpLoadFP(@RequestParam MultipartFile btnFile,HttpServletRequest request,HttpServletResponse response)
	{
		String fileName = btnFile.getOriginalFilename();
        String ret = FileUpload.writeFile(btnFile, fileName);
        String salesOrderID = request.getParameter("tSalesOrderPaymentID");
	}
	
	@RequestMapping(value = "/orderFileUpLoadBG", method = {RequestMethod.GET, RequestMethod.POST})	
	public void orderFileUpLoadBG(@RequestParam MultipartFile btnFileBG1,HttpServletRequest request,HttpServletResponse response)
	{
		String fileName = btnFileBG1.getOriginalFilename();
        String ret = FileUpload.writeFile(btnFileBG1, fileName);
        String salesOrderID = request.getParameter("tSalesOrderPaymentID");
	}
	
	
	
	
}
